package cn.net.withub.dataCollector.web.collector;


import com.gargoylesoftware.htmlunit.BrowserVersion;
import java.util.Set;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

/**
 * 新浪微博
 * 利用Selenium获取登陆新浪微博weibo.cn的cookie(WeiboCN.java)
 * 利用WebCollector和获取的cookie爬取新浪微博并抽取数据(WeiboCrawler.java)
 * 该登录算法适用时间: 2017-6-2 —— ?
 */
public class WeiboCN {
    private Logger log = Logger.getLogger(this.getClass());
    /**
     * 获取新浪微博的cookie，这个方法针对weibo.cn有效，
     * 对weibo.com无效 weibo.cn以明文形式传输数据，请使用小号
     * @param username 新浪微博用户名
     * @param password 新浪微博密码
     */
    public static String getSinaCookie(String username, String password) throws Exception {
        //System.setProperty("webdriver.firefox.bin","E:\\软件安装目录\\Firefox\firefox.exe");
        System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");

        WebDriver driver1 = new HtmlUnitDriver(false);
        driver1.get("https://www.baidu.com");
        String html = driver1.getPageSource();
        System.out.println("html>>"+html);
        HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
        //HtmlUnitDriver driver = new HtmlUnitDriver();
        //WebDriver driver = new FirefoxDriver();
        driver.setJavascriptEnabled(true);
        System.out.println(HttpClientBuilder.class.getProtectionDomain().getCodeSource().getLocation());
        driver.get("https://passport.weibo.cn/signin/login");
        driver.executeScript("document.getElementById('loginWrapper').style.display = 'block'");
        WebElement mobile = driver.findElementByCssSelector("input#loginName");
        mobile.sendKeys(username);
        WebElement pass = driver.findElementByCssSelector("input#loginPassword");
        pass.sendKeys(password);
        WebElement submit = driver.findElementByCssSelector("a#loginAction");
        submit.click();
        String result = concatCookie(driver);
        System.out.println("获取新浪微博Cookie: " + result);
        driver.close();
        if(result.contains("SUB")){
            return result;
        }else {
            throw new Exception("登录失败!");
        }
    }
    public static String concatCookie(HtmlUnitDriver driver) {
        Set<Cookie> cookieSet = driver.manage().getCookies();
        StringBuilder sb = new StringBuilder();
        for (Cookie cookie : cookieSet) {
            sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
        }
        String result = sb.toString();
        return result;
    }
}
